package me.boot.web.security.cors;

import lombok.extern.slf4j.Slf4j;
import me.boot.web.security.cors.properties.CorsProperties;
import me.boot.web.security.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.PostConstruct;

/**
 * attention:简单跨域就是GET，HEAD和POST请求，但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
 * 反之，就是非简单跨域，此跨域有一个预检机制，说直白点，就是会发两次请求，一次OPTIONS请求，一次真正的请求
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({CorsProperties.class})
public class CorsConfiguration {

    @Autowired
    CorsProperties properties;

    @PostConstruct
    void init() {
        log.info("Init CorsConfiguration");
    }

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final org.springframework.web.cors.CorsConfiguration config = new org.springframework.web.cors.CorsConfiguration();
        source.registerCorsConfiguration("/**", config);

        config.setAllowCredentials(properties.isAllowCredentials());
        config.setAllowedOrigins(Util.convertList(properties.getAllowedOrigins()));
        config.setAllowedHeaders(Util.convertList(properties.getAllowedHeaders()));
        config.setAllowedMethods(Util.convertList(properties.getAllowedMethods()));
        config.setExposedHeaders(Util.convertList(properties.getExposedHeaders()));
        config.setMaxAge(properties.getMaxAge());
        return new CorsFilter(source);
    }
}
